<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入订单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="创建人" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="daterangeCreateDate" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="修改人" prop="modifyBy">
        <el-input v-model="queryParams.modifyBy" placeholder="请输入修改人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="修改时间">
        <el-date-picker v-model="daterangeModifyDate" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="客户" prop="cusName">
        <el-input v-model="queryParams.cusName" placeholder="请输入客户" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="审核人" prop="auditName">
        <el-input v-model="queryParams.auditName" placeholder="请输入审核人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['xiaoshou:saleRequest:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['xiaoshou:saleRequest:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['xiaoshou:saleRequest:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['xiaoshou:saleRequest:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="saleRequestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column fixed prop="code" label="单据编号">
        <template slot-scope="scope">
          <orderView :data="scope.row" />
        </template>
      </el-table-column>
      <el-table-column label="客户" align="center" prop="cusName" />
      <el-table-column label="成本总价" align="center" prop="costPrice">
        <template slot-scope="scope">
         {{scope.row.costPrice}}元
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="modifyBy" />
      <el-table-column label="修改时间" align="center" prop="modifyDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modifyDate, '{y}-{m}-{d} ') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 0" style="color: orange;">待审核</span>
          <span v-else-if="scope.row.status === 1" style="color: green;">审核通过</span>
          <span v-else-if="scope.row.status === 2" style="color: red;">已驳回</span>
          <span v-else-if="scope.row.status === 3" style="color: aqua;">已生成订单</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="auditName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="showView(scope.row)" :disabled="scope.row.status!=0">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['xiaoshou:saleRequest:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改销售申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      客户： <el-select v-model="cusId" placeholder="请选择客户">
        <el-option v-for="item in cusList" :key="item.id" :label="item.cusName" :value="item.id">
        </el-option>
      </el-select>
      总金额：{{ totalPrice }}元
      <AddGoods :addGoodsToOrder="addGoodsToOrder" />
      <el-table :data="orderDetail.items" border style="width: 100%">
        <el-table-column prop="proName" label="商品名">
        </el-table-column>
        <el-table-column label="数量">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.count" placeholder="请输入数量" @input="calculateSubtotal(scope.row)">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column prop="unitName" label="单位">
        </el-table-column>
        <el-table-column label="单价">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.price" placeholder="请输入单价" @input="calculateSubtotal(scope.row)">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="小计">
          <template slot-scope="scope">
            {{ scope.row.subtotal }} 元
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addOrder()">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改销售申请详情" :visible.sync="dialogVisible" width="50%" :before-close="handleClose"
      :modal-append-to-body="false" :append-to-body="true">
      <div>
        <template>
          <div>
            <el-descriptions>
              <el-descriptions-item label="单据编号" content-class-name="my-content">{{
                data.code
              }}</el-descriptions-item>
              <el-descriptions-item label="单据日期">{{
                data.createDate
              }}</el-descriptions-item>
              <el-descriptions-item label="客户">{{
                data.cusName
              }}</el-descriptions-item>
              <el-descriptions-item label="业务员">{{
                data.createBy
              }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <span :style="getStatusStyle(data.status)">
                  {{ getStatusText(data.status) }}
                </span>
              </el-descriptions-item>
              <el-descriptions-item label="总金额">{{
                totalPrice
              }}元</el-descriptions-item>
              <el-descriptions-item label="审批人">{{
                data.auditName
              }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </template>
        <AddGoods :orderId="data.id" :addGoodsToOrder="addGoodsToOrder" />
        <el-table :data="orderDetail.items" border style="width: 100%">
          <el-table-column prop="proName" label="商品名">
          </el-table-column>
          <el-table-column label="数量">
            <template slot-scope="scope">
              <el-input v-model="scope.row.count" placeholder="请输入数量" @input="calculateSubtotal(scope.row)">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="unitName" label="单位">
          </el-table-column>
          <el-table-column label="单价">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price" placeholder="请输入单价" @input="calculateSubtotal(scope.row)">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="小计">
            <template slot-scope="scope">
              {{ scope.row.subtotal }} 元
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit()">修 改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listSaleRequest, addOrder, getAllCus, updDetail, getSaleRequest, delSaleRequest, addSaleRequest, updateSaleRequest, saleRequestList } from "@/api/xiaoshou/saleRequest";
import OrderView from "./OrderView.vue"
import AddGoods from "./AddGoods.vue"
export default {
  name: "SaleRequest",
  dicts: ['sys_job_status'],
  components: { OrderView, AddGoods },
  data() {
    return {
      cusList: '',
      cusId: '',
      dialogVisible: false,
      statusName: '',
      orderDetail: {
        items: []
      },
      totalPrice: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售申请表格数据
      saleRequestList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      data: {},
      addOrderDto: {
        proName: '',
        orderDetail: [],
        cusId:0
      },

      // 审核人时间范围
      daterangeCreateDate: [],
      // 审核人时间范围
      daterangeModifyDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: null,
        createBy: null,
        createDate: null,
        modifyBy: null,
        modifyDate: null,
        cusName: null,
        auditName: null,
        code: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        count: [
          { required: true, message: '数量不能为空', trigger: 'blur' },
          { type: 'number', message: '数量必须为数字', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '单价不能为空', trigger: 'blur' },
          { type: 'number', message: '单价必须为数字', trigger: 'blur' }
        ]
      },
      options: [{
        value: '0',
        label: '待审核'
      }, {
        value: '1',
        label: '已审核'
      }, {
        value: '2',
        label: '已驳回'
      },
      {
        value: '3',
        label: '已生成订单'
      },
      ],
    };
  },
  created() {
    this.getList();
    this.getCusList();
  },
  methods: {
    calculateSubtotal(row) {
      if (row.count && row.price) {
        row.subtotal = row.count * row.price;
      } else {
        row.subtotal = 0;
      }
      if(this.orderDetail.items!=null){
        this.totalPrice = this.orderDetail.items.reduce((acc, item) => acc + item.subtotal, 0);
      }

    },
    addGoodsToOrder(selectedGoods) {
      selectedGoods.forEach(good => {
        if (this.orderDetail.items == []) {
          this.orderDetail.items.push({
            proId: good.id,
            proName: good.proName,
            unitName: good.unitName,
            count: 0,
            price: 0.00
          });
        } else {
          let existingItemIndex = this.orderDetail.items.findIndex(item => item.id === good.id);
          if (existingItemIndex === -1) {
            // 商品不存在，添加新的条目
            this.orderDetail.items.push({
              proId: good.id,
              proName: good.proName,
              unitName: good.unitName,
              count: 0,
              price: 0.00
            });
          }
        }
      })
    },
    handleSubmit() {
      for (let i = 0; i < this.orderDetail.items.length; i++) {
        const item = this.orderDetail.items[i];
        if (!this.isNonEmptyInteger(item.count)) {
          alert("请输入正确的数量");
          item.count = 1;
          return; // 退出整个函数
        }
        if (!this.isNonNegativeNumber(item.price)) {
          alert("请输入正确的价格");
          item.price = 100; // 默认价格
          return; // 退出整个函数
        }
        item.orderId = this.data.id;
      }
      updDetail(this.orderDetail.items).then(response => {
        alert("修改成功");
        this.dialogVisible = false;
        this.getList();
      });
    },
    //获取客户列表
    getCusList() {
      getAllCus().then(response => {
        this.cusList = response.data;
      });
    },
    isNonEmptyInteger(value) {
      const regex = /^[1-9]\d*$/;
      return regex.test(String(value));
    },
    isNonNegativeNumber(value) {
      const regex = /^[1-9]\d*(\.\d+)?$/;
      return regex.test(String(value));
    },
    handleClose(done) {
      done();
    },
    showView(order) {
      if (order.status == 1 || order.status == 3) {
        alert("该申请已通过审核或已生成订单，不能修改");
        return;
      }
      this.data = order;
      this.dialogVisible = true;
      saleRequestList(order.id).then(response => {
        this.orderDetail.items = response.data;
        this.totalPrice = this.orderDetail.items.reduce((acc, item) => acc + item.subtotal, 0);
      });
    },
    getStatusText(status) {
      const statusMap = {
        0: '待审核',
        1: '已审核',
        2: '已驳回',
      };
      return statusMap[status] || '已生成订单';
    },
    getStatusStyle(status) {
      const statusMap = {
        0: 'color: orange;',
        1: 'color: green;',
        2: 'color: red;',
        3: 'color: aqua;',
      };
      return statusMap[status] || 'color: black;';

    },
    //添加销售申请
    addOrder() {
      if (this.cus == '') {
        alert("请选择客户");
        return;
      }
      for (let i = 0; i < this.orderDetail.items.length; i++) {
        const item = this.orderDetail.items[i];
        if (!this.isNonEmptyInteger(item.count)) {
          alert("请输入正确的数量");
          item.count = 1;
          return; // 退出整个函数
        }
        if (!this.isNonNegativeNumber(item.price)) {
          alert("请输入正确的价格");
          item.price = 100; // 默认价格
          return; // 退出整个函数
        }
      }
      
      this.addOrderDto.cusId = this.cusId;
      const customer = this.cusList.find(item => item.id === this.cusId);
      if (customer) {
        this.addOrderDto.cusName = customer.cusName;
      }
      this.cusName = '';
      this.addOrderDto.orderDetail = this.orderDetail.items;
      addOrder(this.addOrderDto).then(response => {
        alert("添加成功");
        this.orderDetail.items = [];
        this.cusName = '';
        this.getList();
        this.open=false;
      });
    },
    /** 查询销售申请列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateDate && '' != this.daterangeCreateDate) {
        this.queryParams.params["beginCreateDate"] = this.daterangeCreateDate[0];
        this.queryParams.params["endCreateDate"] = this.daterangeCreateDate[1];
      }
      if (null != this.daterangeModifyDate && '' != this.daterangeModifyDate) {
        this.queryParams.params["beginModifyDate"] = this.daterangeModifyDate[0];
        this.queryParams.params["endModifyDate"] = this.daterangeModifyDate[1];
      }
      listSaleRequest(this.queryParams).then(response => {
        this.saleRequestList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        status: null,
        createBy: null,
        createDate: null,
        modifyBy: null,
        modifyDate: null,
        isDel: null,
        cusName: null,
        auditName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateDate = [];
      this.daterangeModifyDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.orderDetail.items = [];
      this.total = 0;
      this.open = true;
      this.title = "添加销售申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSaleRequest(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改销售申请";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除销售申请编号为"' + ids + '"的数据项？').then(function () {
        return delSaleRequest(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('xiaoshou/saleRequest/export', {
        ...this.queryParams
      }, `saleRequest_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
